package com.mxfcode.back.controller;


import com.mxfcode.back.service.FileService;
import com.mxfcode.entity.BBSAttachment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;


@Controller
@RequestMapping("/file")
public class FileController {

	@Autowired
	private FileService fileService;

	@RequestMapping(value="/uploadSource" , method = RequestMethod.POST)
	@ResponseBody
	public String uploadSource(@RequestParam("file") MultipartFile file) {
		System.out.println(file);
		String pathString = null;
		if(file!=null) {
			//获取上传的文件名称
			String filename = file.getOriginalFilename();
			//文件上传时，chrome与IE/Edge对于originalFilename处理方式不同
			//chrome会获取到该文件的直接文件名称，IE/Edge会获取到文件上传时完整路径/文件名
			//Check for Unix-style path
			int unixSep = filename.lastIndexOf('/');
			//Check for Windows-style path
			int winSep = filename.lastIndexOf('\\');
			//cut off at latest possible point
			int pos = (winSep > unixSep ? winSep:unixSep);
			if (pos != -1) {
				filename = filename.substring(pos + 1);
			}
			pathString = "D:/upload/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" +filename;//上传到本地
		}
		try {
			File files=new File(pathString);//在内存中创建File文件映射对象
			//打印查看上传路径
			System.out.println(pathString);
			if(!files.getParentFile().exists()){//判断映射文件的父文件是否真实存在
				files.getParentFile().mkdirs();//创建所有父文件夹
			}
			file.transferTo(files);//采用file.transferTo 来保存上传的文件
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "{\"code\":0, \"msg\":\"success\", \"fileUrl\":\"" + pathString + "\"}";
	}

	@RequestMapping("paperupload")
	@ResponseBody
	public String paperupload(MultipartFile file){
		System.out.println(file);
		String pathString=null;
		String nowid=null;//要返回给前端的上传的文件在文件表中的id
		if(file!=null){
			//获取上传的文件名称
			String filename = file.getOriginalFilename();
			//文件上传时，chrome与IE/Edge对于originalFilename处理方式不同
			//chrome会获取到该文件的直接文件名称，IE/Edge会获取到文件上传时完整路径/文件名
			//Check for Unix-style path
			int unixSep = filename.lastIndexOf('/');
			//Check for Windows-style path
			int winSep = filename.lastIndexOf('\\');
			//cut off at latest possible point
			int pos = (Math.max(winSep, unixSep));
			if (pos != -1){
				filename = filename.substring(pos + 1);
			}
			String savename=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" +filename;
			pathString = "D:/upload/" + savename;//上传到本地
			//保存到数据库中
			int a=fileService.addFile(filename,pathString,savename);
			System.out.println("文件添加结果："+a);
			//然后获取信息
			BBSAttachment attachment=fileService.getFileInfoBySaveName(savename);
			nowid= String.valueOf(attachment.getId());
			//打印id
			System.out.println("nowid:"+nowid);
		}
		try {
			File files=new File(pathString);//在内存中创建File文件映射对象
			//打印查看上传路径
			System.out.println(pathString);
			if(!files.getParentFile().exists()){//判断映射文件的父文件是否真实存在
				files.getParentFile().mkdirs();//创建所有父文件夹
			}
			file.transferTo(files);//采用file.transferTo 来保存上传的文件
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "{\"code\":0, \"msg\":\"success\", \"fileUrl\":\"" + pathString + "\",\"id\":\""+nowid+"\"}";
	}

    @RequestMapping(path = "/download")
    public void downloadLocal(HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException {

        String saveName = request.getParameter("saveName");
        BBSAttachment file = fileService.getFileInfoBySaveName(saveName);
        // 下载本地文件
        String fileName = file.getResourceName().toString(); // 文件的默认保存名
        // 读到流中
        InputStream inStream = new FileInputStream(file.getResourceUrl());// 文件的存放路径
        // 设置输出的格式
        response.reset();
        response.setContentType("bin");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len;
        try {
            while ((len = inStream.read(b)) > 0){
                response.getOutputStream().write(b, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}